<template>
  <div class="dashboard">
    <!-- 欢迎横幅 -->
    <div class="welcome-banner">
      <div class="banner-content">
        <div class="banner-left">
          <div class="greeting">
            <div class="greeting-animation">
              <h1 class="main-title">{{ greeting }}，{{ currentUser }}！ 👋</h1>
              <div class="title-underline"></div>
            </div>
            <p class="date-info">
              <el-icon class="weather-icon">
                <component :is="weatherData.icon" />
              </el-icon>
              {{ currentDate }} | {{ weatherData.description }} {{ weatherData.temperature }}°C
            </p>
            <p class="subtitle">今天也要努力工作，查看您的数据概览</p>
            <div class="quick-stats">
              <div class="quick-stat-item">
                <span class="quick-stat-number">{{ displayStats.activeUsers }}</span>
                <span class="quick-stat-label">活跃用户</span>
              </div>
              <div class="quick-stat-item">
                <span class="quick-stat-number">{{ formatNumber(displayStats.todayActive) }}</span>
                <span class="quick-stat-label">今日活跃</span>
              </div>
            </div>
          </div>
        </div>
        <div class="banner-right">
          <div class="action-buttons">
            <el-button v-if="userStore.hasPermission('user.view')" type="primary" class="action-btn gradient-blue"
              @click="handleAddUser">
              <el-icon>
                <Plus />
              </el-icon>
              新增用户
            </el-button>
            <el-button v-if="userStore.hasPermission('permission.view')" type="success"
              class="action-btn gradient-green" @click="handlePermissionManagement">
              <el-icon>
                <Document />
              </el-icon>
              权限管理
            </el-button>
            <el-button v-if="userStore.hasPermission('system.settings')" type="warning"
              class="action-btn gradient-orange" @click="handleSystemSettings">
              <el-icon>
                <Setting />
              </el-icon>
              系统设置
            </el-button>
          </div>
          <div class="banner-decoration">
            <div class="floating-card card-1">
              <div class="card-icon">📊</div>
              <div class="card-text">数据分析</div>
            </div>
            <div class="floating-card card-2">
              <div class="card-icon">🚀</div>
              <div class="card-text">性能优秀</div>
            </div>
            <div class="floating-card card-3">
              <div class="card-icon">⚡</div>
              <div class="card-text">运行稳定</div>
            </div>
          </div>
        </div>
      </div>
      <div class="banner-bg-elements">
        <div class="bg-circle circle-1"></div>
        <div class="bg-circle circle-2"></div>
        <div class="bg-circle circle-3"></div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-container">
      <div class="stat-card users-card fade-in-up" style="animation-delay: 0.1s">
        <div class="stat-icon">
          <el-icon class="stat-icon-svg">
            <User />
          </el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ formatNumber(displayStats.totalUsers) }}</div>
          <div class="stat-label">总用户数</div>
        </div>
        <div class="stat-chart">
          <div class="mini-chart blue">
            <div class="chart-wave wave-1"></div>
            <div class="chart-wave wave-2"></div>
          </div>
        </div>
      </div>

      <div class="stat-card visits-card fade-in-up" style="animation-delay: 0.2s">
        <div class="stat-icon">
          <el-icon class="stat-icon-svg">
            <UserFilled />
          </el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ formatNumber(displayStats.activeUsers) }}</div>
          <div class="stat-label">活跃用户</div>
        </div>
        <div class="stat-chart">
          <div class="mini-chart green">
            <div class="chart-wave wave-1"></div>
            <div class="chart-wave wave-2"></div>
          </div>
        </div>
      </div>

      <div class="stat-card pageviews-card fade-in-up" style="animation-delay: 0.3s">
        <div class="stat-icon">
          <el-icon class="stat-icon-svg">
            <User />
          </el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ formatNumber(displayStats.newUsers) }}</div>
          <div class="stat-label">新增用户</div>
        </div>
        <div class="stat-chart">
          <div class="mini-chart orange">
            <div class="chart-wave wave-1"></div>
            <div class="chart-wave wave-2"></div>
          </div>
        </div>
      </div>

      <div class="stat-card time-card fade-in-up" style="animation-delay: 0.4s">
        <div class="stat-icon">
          <el-icon class="stat-icon-svg">
            <Odometer />
          </el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ formatNumber(displayStats.totalLogins) }}</div>
          <div class="stat-label">总登录次数</div>
        </div>
        <div class="stat-chart">
          <div class="mini-chart red">
            <div class="chart-wave wave-1"></div>
            <div class="chart-wave wave-2"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 快捷操作和系统状态 -->
    <div class="additional-content">
      <!-- 快捷操作面板 -->
      <div class="quick-actions-panel">
        <div class="panel-header">
          <h3>⚡ 快捷操作</h3>
          <p>常用功能快速入口</p>
        </div>
        <div class="quick-actions-grid">
          <div class="action-item fade-in-up" v-for="(action, index) in quickActions" :key="action.id"
            @click="handleQuickAction(action)" :style="{ 'animation-delay': `${0.3 + index * 0.1}s` }">
            <div class="action-icon" :style="{ background: action.color }">
              <el-icon :size="24">
                <component :is="action.icon" />
              </el-icon>
            </div>
            <div class="action-info">
              <div class="action-name">{{ action.name }}</div>
              <div class="action-desc">{{ action.description }}</div>
            </div>
            <div class="action-arrow">
              <el-icon>
                <ArrowRight />
              </el-icon>
            </div>
          </div>
        </div>
      </div>

      <!-- 系统状态监控 -->
      <div class="system-status-panel">
        <div class="panel-header">
          <h3>🖥️ 系统状态</h3>
          <p>实时系统运行状况</p>
        </div>
        <div class="status-grid">
          <div class="status-item fade-in-up" style="animation-delay: 0.6s">
            <div class="status-indicator healthy">
              <div class="pulse-dot"></div>
            </div>
            <div class="status-info">
              <div class="status-title">服务器状态</div>
              <div class="status-value">运行正常</div>
            </div>
            <div class="status-chart">
              <div class="mini-progress" :style="`--progress: 95%`">95%</div>
            </div>
          </div>

          <div class="status-item fade-in-up" style="animation-delay: 0.7s">
            <div class="status-indicator warning">
              <div class="pulse-dot"></div>
            </div>
            <div class="status-info">
              <div class="status-title">内存使用</div>
              <div class="status-value">{{ displaySystemStats.memoryUsage }}%</div>
            </div>
            <div class="status-chart">
              <div class="mini-progress warning" :style="`--progress: ${displaySystemStats.memoryUsage}%`">{{
                displaySystemStats.memoryUsage }}%</div>
            </div>
          </div>

          <div class="status-item fade-in-up" style="animation-delay: 0.8s">
            <div class="status-indicator healthy">
              <div class="pulse-dot"></div>
            </div>
            <div class="status-info">
              <div class="status-title">CPU 使用率</div>
              <div class="status-value">{{ displaySystemStats.cpuUsage }}%</div>
            </div>
            <div class="status-chart">
              <div class="mini-progress" :style="`--progress: ${displaySystemStats.cpuUsage}%`">{{
                displaySystemStats.cpuUsage }}%</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部内容 -->
    <div class="bottom-content">
      <!-- 最近活动 -->
      <div class="recent-activities">
        <div class="panel-header">
          <h3>🕒 最近活动</h3>
          <p>系统操作日志</p>
        </div>
        <div class="activities-list">
          <div class="activity-item fade-in-up" v-for="(activity, index) in recentActivities" :key="activity.id"
            :style="{ 'animation-delay': `${1.2 + index * 0.1}s` }">
            <div class="activity-avatar" :style="{ background: activity.avatarColor }">
              {{ activity.user.charAt(0) }}
            </div>
            <div class="activity-content">
              <div class="activity-text">
                <span class="user-name">{{ activity.user }}</span>
                <span class="activity-action">{{ activity.action }}</span>
                <span class="activity-target">{{ activity.target }}</span>
              </div>
              <div class="activity-time">{{ activity.time }}</div>
            </div>
            <div class="activity-type" :class="activity.type">
              <el-icon>
                <component :is="activity.typeIcon" />
              </el-icon>
            </div>
          </div>
        </div>
        <div class="activities-footer">
          <el-button text type="primary">查看全部活动</el-button>
        </div>
      </div>

      <!-- 通知公告 -->
      <div class="announcements">
        <div class="panel-header">
          <h3>📢 通知公告</h3>
          <p>重要消息提醒</p>
        </div>
        <div class="announcement-list">
          <div class="announcement-item fade-in-up" v-for="(announcement, index) in announcements"
            :key="announcement.id" :style="{ 'animation-delay': `${1.5 + index * 0.15}s` }">
            <div class="announcement-indicator" :class="announcement.priority">
              <div class="indicator-dot"></div>
            </div>
            <div class="announcement-content">
              <div class="announcement-title">{{ announcement.title }}</div>
              <div class="announcement-preview">{{ announcement.preview }}</div>
              <div class="announcement-meta">
                <span class="announcement-date">{{ announcement.date }}</span>
                <span class="announcement-category">{{ announcement.category }}</span>
              </div>
            </div>
            <div class="announcement-actions">
              <el-button size="small" text>查看</el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 数据概览小组件 -->
      <div class="data-widgets">
        <div class="panel-header">
          <h3>📊 数据概览</h3>
          <p>关键指标汇总</p>
        </div>
        <div class="widgets-grid">
          <div class="widget-item sales-widget">
            <div class="widget-header">
              <div class="widget-icon">💰</div>
              <div class="widget-title">今日销售</div>
            </div>
            <div class="widget-value">¥{{ formatCurrency(todayStats.sales) }}</div>
          </div>

          <div class="widget-item orders-widget">
            <div class="widget-header">
              <div class="widget-icon">📦</div>
              <div class="widget-title">新订单</div>
            </div>
            <div class="widget-value">{{ todayStats.orders }}</div>
          </div>

          <div class="widget-item conversion-widget">
            <div class="widget-header">
              <div class="widget-icon">🎯</div>
              <div class="widget-title">转化率</div>
            </div>
            <div class="widget-value">{{ todayStats.conversion }}%</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { analyticsApi } from '@/api/analytics'
import { systemApi } from '@/api'
import { ElMessage } from 'element-plus'
import {
  Plus,
  Document,
  Setting,
  User,
  View,
  Timer,
  TrendCharts,
  Bottom,
  DataAnalysis,
  Sunny,
  Cloudy,
  Drizzling,
  Lightning,
  ArrowRight,
  UserFilled,
  Files,
  Connection,
  Monitor,
  EditPen,
  Delete,
  Check,
  Warning,
  Odometer
} from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()

// 计算属性：用户名和问候语
const currentUser = computed(() => {
  return userStore.userInfo?.nickName || userStore.userInfo?.username || '用户'
})

const greeting = computed(() => {
  const hour = new Date().getHours()
  if (hour < 12) return '早上好'
  if (hour < 18) return '下午好'
  return '晚上好'
})

const stats = ref({
  totalUsers: 0,
  activeUsers: 0,
  newUsers: 0,
  totalLogins: 0,
  todayActive: 0
})

// 动画显示的数值
const displayStats = ref({
  totalUsers: 0,
  activeUsers: 0,
  newUsers: 0,
  totalLogins: 0,
  todayActive: 0
})

// 动画控制器，用于取消正在进行的动画
const animationControllers = ref(new Map())
const systemAnimationControllers = ref(new Map())

// 数字滚动动画函数
const animateNumber = (from, to, key, duration = 2000) => {
  if (from === to) return

  // 如果该键已有动画在进行，先取消
  if (animationControllers.value.has(key)) {
    animationControllers.value.get(key).cancel = true
  }

  // 创建新的动画控制器
  const controller = { cancel: false }
  animationControllers.value.set(key, controller)

  // 为数字元素添加更新效果类
  const addUpdateEffect = () => {
    const elements = document.querySelectorAll(`.stat-number, .quick-stat-number`)
    elements.forEach(el => {
      if (el.textContent.includes(formatNumber(to)) || el.textContent.includes(to.toString())) {
        el.classList.add('updating')
        setTimeout(() => el.classList.remove('updating'), duration)
      }
    })
  }

  const startTime = Date.now()
  const animate = () => {
    // 检查是否被取消
    if (controller.cancel) {
      animationControllers.value.delete(key)
      return
    }

    const elapsed = Date.now() - startTime
    const progress = Math.min(elapsed / duration, 1)

    // 使用缓动函数
    const easeOutCubic = 1 - Math.pow(1 - progress, 3)
    const current = Math.floor(from + (to - from) * easeOutCubic)

    displayStats.value[key] = current

    if (progress < 1) {
      requestAnimationFrame(animate)
    } else {
      displayStats.value[key] = to
      animationControllers.value.delete(key)
    }
  }

  // 开始动画前添加效果
  addUpdateEffect()
  requestAnimationFrame(animate)
}

// 触发所有数字动画
const animateAllStats = (newStats) => {
  Object.keys(newStats).forEach(key => {
    // 首次加载时从0开始动画
    animateNumber(0, newStats[key], key)
  })
}

const weatherData = ref({
  temperature: 22,
  description: '加载中...',
  icon: 'Sunny'
})

// 加载天气数据
const loadWeatherData = async () => {
  try {
    // 方案1: 先尝试通过IP获取位置（无需授权）
    try {
      const ipResponse = await fetch('https://ipapi.co/json/')
      const ipData = await ipResponse.json()

      if (ipData.latitude && ipData.longitude) {
        console.log('通过IP获取位置:', ipData.city, ipData.country)
        await fetchWeatherByCoords(ipData.latitude, ipData.longitude)
        return
      }
    } catch (error) {
      console.log('IP定位失败，尝试GPS定位')
    }

    // 方案2: 如果IP定位失败，静默尝试GPS（不显示错误）
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        async (position) => {
          const { latitude, longitude } = position.coords
          await fetchWeatherByCoords(latitude, longitude)
        },
        (error) => {
          // 静默处理GPS定位失败，使用默认天气
          console.log('GPS定位失败，使用默认天气')
          setDefaultWeather()
        },
        {
          timeout: 5000,
          enableHighAccuracy: false,
          maximumAge: 600000 // 10分钟缓存
        }
      )
    } else {
      // 浏览器不支持地理位置，使用默认天气
      setDefaultWeather()
    }
  } catch (error) {
    console.error('天气功能初始化失败:', error)
    setDefaultWeather()
  }
}

// 根据坐标获取天气
const fetchWeatherByCoords = async (latitude, longitude) => {
  try {
    const response = await fetch(`https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&current=temperature_2m,weather_code&timezone=auto`)
    const data = await response.json()

    if (data.current) {
      const temp = Math.round(data.current.temperature_2m)
      const weatherCode = data.current.weather_code

      // 根据天气代码映射天气描述和图标
      const weatherMap = {
        0: { desc: '晴朗', icon: 'Sunny' },
        1: { desc: '多云', icon: 'Cloudy' },
        2: { desc: '多云', icon: 'Cloudy' },
        3: { desc: '阴天', icon: 'Cloudy' },
        45: { desc: '雾', icon: 'Cloudy' },
        48: { desc: '雾', icon: 'Cloudy' },
        51: { desc: '小雨', icon: 'Drizzling' },
        53: { desc: '中雨', icon: 'Drizzling' },
        55: { desc: '大雨', icon: 'Drizzling' },
        61: { desc: '小雨', icon: 'Drizzling' },
        63: { desc: '中雨', icon: 'Drizzling' },
        65: { desc: '大雨', icon: 'Drizzling' },
        80: { desc: '阵雨', icon: 'Drizzling' },
        81: { desc: '阵雨', icon: 'Drizzling' },
        82: { desc: '暴雨', icon: 'Lightning' },
        95: { desc: '雷雨', icon: 'Lightning' },
        96: { desc: '雷雨', icon: 'Lightning' },
        99: { desc: '雷雨', icon: 'Lightning' }
      }

      const weather = weatherMap[weatherCode] || { desc: '未知', icon: 'Sunny' }

      weatherData.value = {
        temperature: temp,
        description: weather.desc,
        icon: weather.icon
      }

      console.log('天气数据加载成功:', weatherData.value)
    }
  } catch (error) {
    console.error('获取天气数据失败:', error)
    setDefaultWeather()
  }
}

// 设置默认天气
const setDefaultWeather = () => {
  // 根据季节设置默认天气
  const month = new Date().getMonth() + 1
  let defaultTemp = 22
  let defaultDesc = '晴朗'

  // 简单的季节判断
  if (month >= 12 || month <= 2) {
    defaultTemp = 8 // 冬季
    defaultDesc = '多云'
  } else if (month >= 3 && month <= 5) {
    defaultTemp = 18 // 春季
    defaultDesc = '晴朗'
  } else if (month >= 6 && month <= 8) {
    defaultTemp = 28 // 夏季
    defaultDesc = '晴朗'
  } else {
    defaultTemp = 20 // 秋季
    defaultDesc = '多云'
  }

  weatherData.value = {
    temperature: defaultTemp,
    description: defaultDesc,
    icon: defaultDesc === '晴朗' ? 'Sunny' : 'Cloudy'
  }
}
const loadDashboardData = async () => {
  try {
    const response = await analyticsApi.getDashboardData('7d')
    console.log('仪表板API响应:', response)

    // 处理后端的实际响应格式
    if (response && (response.code === 200 || response.data?.code === 200)) {
      const data = response.data || response.Data || response

      // 新的统计数据
      const newStats = {
        totalUsers: data.TotalUsers || data.totalUsers || 0,
        activeUsers: data.ActiveUsers || data.activeUsers || 0,
        newUsers: data.NewUsers || data.newUsers || 0,
        totalLogins: data.TotalLogins || data.totalLogins || 0,
        todayActive: data.TodayActiveUsers || data.todayActiveUsers || 0
      }

      // 检查是否是首次加载（显示值都是0）
      const isFirstLoad = Object.values(displayStats.value).every(val => val === 0)

      // 更新实际数据
      const prevStats = { ...stats.value }
      stats.value = newStats

      if (isFirstLoad) {
        // 首次加载，确保显示值从0开始，然后动画到目标值
        Object.keys(newStats).forEach(key => {
          displayStats.value[key] = 0
        })
        // 延迟一帧，确保UI更新后再开始动画
        nextTick(() => {
          animateAllStats(newStats)
        })
      } else {
        // 检查哪些数据发生了变化
        const changedStats = {}
        Object.keys(newStats).forEach(key => {
          if (prevStats[key] !== newStats[key]) {
            changedStats[key] = newStats[key]
          }
        })

        // 只对变化的数据进行动画
        if (Object.keys(changedStats).length > 0) {
          Object.keys(changedStats).forEach(key => {
            animateNumber(displayStats.value[key], changedStats[key], key)
          })
        }
      }

      console.log('仪表板数据加载成功:', newStats)
    } else {
      console.error('仪表板API返回错误:', response)
      ElMessage.error('获取仪表板数据失败')
    }
  } catch (error) {
    console.error('加载仪表板数据失败:', error)
    // 检查是否是拦截器的问题
    if (error.message === '成功') {
      console.log('API请求成功，但被拦截器误判为错误')
      return
    }
    ElMessage.error('无法连接到后端服务，请检查网络连接')
  }
}

// 新增数据
const quickActions = ref([
  {
    id: 1,
    name: '智能组件中心',
    description: '一站式高效组件集成与管理',
    icon: 'Histogram',
    color: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    route: '/home/component-center'
  },
  {
    id: 2,
    name: '模板云库',
    description: '行业级模板沉淀与创新应用',
    icon: 'Grid',
    color: 'linear-gradient(135deg, #10b981 0%, #34d399 100%)',
    route: '/home/template-center'
  },
  {
    id: 3,
    name: '智能数据洞察',
    description: '多维度数据分析与智能决策',
    icon: 'TrendCharts',
    color: 'linear-gradient(135deg, #f59e0b 0%, #fbbf24 100%)',
    route: '/home/analytics'
  },
  {
    id: 4,
    name: '个人数字空间',
    description: '专属信息中心与个性化设置',
    icon: 'User',
    color: 'linear-gradient(135deg, #ef4444 0%, #f87171 100%)',
    route: '/home/profile'
  }
])

const systemStats = ref({
  memoryUsage: 0,
  cpuUsage: 0,
  diskUsage: 0
})

// 显示用的系统状态数据（支持动画）
const displaySystemStats = ref({
  memoryUsage: 0,
  cpuUsage: 0,
  diskUsage: 0
})

// 系统状态数字动画函数
const animateSystemStat = (from, to, key, duration = 1500) => {
  if (from === to) return

  // 如果该键已有动画在进行，先取消
  if (systemAnimationControllers.value.has(key)) {
    systemAnimationControllers.value.get(key).cancel = true
  }

  // 创建新的动画控制器
  const controller = { cancel: false }
  systemAnimationControllers.value.set(key, controller)

  const startTime = Date.now()
  const animate = () => {
    // 检查是否被取消
    if (controller.cancel) {
      systemAnimationControllers.value.delete(key)
      return
    }

    const elapsed = Date.now() - startTime
    const progress = Math.min(elapsed / duration, 1)

    // 使用缓动函数
    const easeOutQuart = 1 - Math.pow(1 - progress, 4)
    const current = parseFloat((from + (to - from) * easeOutQuart).toFixed(1))

    displaySystemStats.value[key] = current

    if (progress < 1) {
      requestAnimationFrame(animate)
    } else {
      displaySystemStats.value[key] = to
      systemAnimationControllers.value.delete(key)
    }
  }
  requestAnimationFrame(animate)
}

// 触发系统状态动画
const animateSystemStats = (newStats) => {
  Object.keys(newStats).forEach(key => {
    // 首次加载时从0开始动画
    animateSystemStat(0, newStats[key], key)
  })
}

// 加载系统状态数据
const loadSystemStats = async () => {
  try {
    // 使用与监控页面相同的API接口，确保数据完全同步
    const response = await systemApi.getPerformanceMetrics()
    console.log('仪表盘系统状态API响应:', response)

    // 处理系统性能API的响应格式
    if ((response.isSuccess || response.success) && response.data) {
      const data = response.data

      // 计算内存使用率百分比
      const memoryUsagePercent = data.memoryTotal > 0
        ? Math.round((data.memoryUsed / data.memoryTotal) * 100)
        : 0

      // 计算磁盘使用率百分比  
      const diskUsagePercent = data.diskTotal > 0
        ? Math.round((data.diskUsed / data.diskTotal) * 100)
        : 0

      // 直接使用后端返回的CPU使用率
      const cpuUsagePercent = Math.round(data.cpuUsage || 0)

      const newSystemStats = {
        memoryUsage: memoryUsagePercent,
        cpuUsage: cpuUsagePercent,
        diskUsage: diskUsagePercent
      }

      console.log('仪表盘计算后的系统指标:', {
        '后端CPU': data.cpuUsage,
        '仪表盘CPU': cpuUsagePercent,
        '后端内存使用': data.memoryUsed,
        '后端内存总量': data.memoryTotal,
        '仪表盘内存使用率': memoryUsagePercent,
        '后端磁盘使用': data.diskUsed,
        '后端磁盘总量': data.diskTotal,
        '仪表盘磁盘使用率': diskUsagePercent
      })

      // 检查是否是首次加载
      const isFirstLoad = Object.values(displaySystemStats.value).every(val => val === 0)

      // 更新实际数据
      const prevSystemStats = { ...systemStats.value }
      systemStats.value = newSystemStats

      if (isFirstLoad) {
        // 首次加载，确保显示值从0开始，然后动画到目标值
        Object.keys(newSystemStats).forEach(key => {
          displaySystemStats.value[key] = 0
        })
        // 延迟一帧，确保UI更新后再开始动画
        nextTick(() => {
          animateSystemStats(newSystemStats)
        })
      } else {
        // 检查哪些数据发生了变化
        const changedStats = {}
        Object.keys(newSystemStats).forEach(key => {
          if (prevSystemStats[key] !== newSystemStats[key]) {
            changedStats[key] = newSystemStats[key]
          }
        })

        // 只对变化的数据进行动画
        if (Object.keys(changedStats).length > 0) {
          Object.keys(changedStats).forEach(key => {
            animateSystemStat(displaySystemStats.value[key], changedStats[key], key)
          })
        }
      }

      console.log('系统状态数据加载成功:', newSystemStats)
    } else {
      console.error('系统状态API返回错误:', response)
    }
  } catch (error) {
    console.error('加载系统状态失败:', error)
    // 检查是否是拦截器的问题
    if (error.message === '成功') {
      console.log('系统状态API请求成功，但被拦截器误判为错误')
      return
    }
    // 使用模拟数据
    const mockSystemStats = {
      memoryUsage: parseFloat((Math.random() * 30 + 60).toFixed(1)), // 60-90%
      cpuUsage: parseFloat((Math.random() * 40 + 10).toFixed(1)),    // 10-50%
      diskUsage: parseFloat((Math.random() * 20 + 30).toFixed(1))    // 30-50%
    }
    systemStats.value = mockSystemStats
    animateSystemStats(mockSystemStats)
  }
}

const recentActivities = ref([
  {
    id: 1,
    user: '张三',
    action: '创建了新用户',
    target: '李四',
    time: '2分钟前',
    type: 'create',
    typeIcon: 'Plus',
    avatarColor: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
  },
  {
    id: 2,
    user: '王五',
    action: '修改了数据',
    target: '用户配置',
    time: '5分钟前',
    type: 'edit',
    typeIcon: 'EditPen',
    avatarColor: 'linear-gradient(135deg, #10b981 0%, #34d399 100%)'
  },
  {
    id: 3,
    user: '赵六',
    action: '删除了记录',
    target: '过期日志',
    time: '10分钟前',
    type: 'delete',
    typeIcon: 'Delete',
    avatarColor: 'linear-gradient(135deg, #ef4444 0%, #f87171 100%)'
  }
])

const announcements = ref([
  {
    id: 1,
    title: '系统维护通知',
    preview: '将于今晚 23:00-01:00 进行系统维护，期间可能影响部分功能使用...',
    date: '2025-07-21',
    category: '系统公告',
    priority: 'high'
  },
  {
    id: 2,
    title: '新功能上线',
    preview: 'V2.1.0 版本已发布，新增数据可视化功能和性能优化...',
    date: '2025-07-20',
    category: '版本更新',
    priority: 'medium'
  }
])

const todayStats = ref({
  sales: 0,
  salesGrowth: 0,
  orders: 0,
  ordersGrowth: 0,
  conversion: 0,
  conversionDrop: 0
})

// 角色统计数据
const roleStats = ref({
  totalRoles: 0,
  activeRoles: 0,
  inactiveRoles: 0
})

// 动画显示的角色统计数据
const displayRoleStats = ref({
  totalRoles: 0,
  activeRoles: 0,
  inactiveRoles: 0
})

// 日志统计数据  
const logStats = ref({
  errors: 0,
  warnings: 0,
  infos: 0,
  debugs: 0
})

// 动画显示的日志统计数据
const displayLogStats = ref({
  errors: 0,
  warnings: 0,
  infos: 0,
  debugs: 0
})

const loadBusinessStats = async () => {
  try {
    const response = await analyticsApi.getDashboardData('1d')
    console.log('业务数据API响应:', response)

    // 处理后端的实际响应格式
    if (response && (response.code === 200 || response.data?.code === 200)) {
      const data = response.data || response.Data || response

      todayStats.value = {
        sales: data.RevenueData?.totalRevenue || data.revenueData?.totalRevenue || 0,
        salesGrowth: data.RevenueData?.growthRate || data.revenueData?.growthRate || 0,
        orders: data.TotalSessions || data.totalSessions || 0,
        ordersGrowth: data.SessionGrowthRate || data.sessionGrowthRate || 0,
        conversion: ((data.ConversionRate || data.conversionRate || 0) * 100),
        conversionDrop: 0 // 计算转化率下降
      }
      console.log('业务数据加载成功:', todayStats.value)
    } else {
      console.error('业务数据API返回错误:', response)
    }
  } catch (error) {
    console.error('加载业务数据失败:', error)
    // 检查是否是拦截器的问题
    if (error.message === '成功') {
      console.log('业务数据API请求成功，但被拦截器误判为错误')
      return
    }
    ElMessage.error('无法获取业务数据')
  }
}

// 加载角色统计数据
const loadRoleStats = async () => {
  try {
    // 这里可以调用角色API获取真实数据
    // const response = await roleApi.getRoleStats()

    // 临时使用模拟数据
    const mockRoleStats = {
      totalRoles: 7,
      activeRoles: 7,
      inactiveRoles: 0
    }

    // 检查是否是首次加载
    const isFirstLoad = Object.values(displayRoleStats.value).every(val => val === 0)

    // 更新实际数据
    const prevRoleStats = { ...roleStats.value }
    roleStats.value = mockRoleStats

    if (isFirstLoad) {
      // 首次加载，确保显示值从0开始，然后动画到目标值
      Object.keys(mockRoleStats).forEach(key => {
        displayRoleStats.value[key] = 0
      })
      // 延迟一帧，确保UI更新后再开始动画
      nextTick(() => {
        animateRoleStats(mockRoleStats)
      })
    } else {
      // 检查哪些数据发生了变化
      const changedStats = {}
      Object.keys(mockRoleStats).forEach(key => {
        if (prevRoleStats[key] !== mockRoleStats[key]) {
          changedStats[key] = mockRoleStats[key]
        }
      })

      // 只对变化的数据进行动画
      if (Object.keys(changedStats).length > 0) {
        Object.keys(changedStats).forEach(key => {
          animateRoleStat(displayRoleStats.value[key], changedStats[key], key)
        })
      }
    }

    console.log('角色统计数据加载成功:', mockRoleStats)
  } catch (error) {
    console.error('加载角色统计失败:', error)
  }
}

// 加载日志统计数据
const loadLogStats = async () => {
  try {
    // 这里可以调用日志API获取真实数据
    // const response = await logApi.getLogStats()

    // 临时使用模拟数据
    const mockLogStats = {
      errors: 3,
      warnings: 2,
      infos: 3,
      debugs: 2
    }

    // 检查是否是首次加载
    const isFirstLoad = Object.values(displayLogStats.value).every(val => val === 0)

    // 更新实际数据
    const prevLogStats = { ...logStats.value }
    logStats.value = mockLogStats

    if (isFirstLoad) {
      // 首次加载，确保显示值从0开始，然后动画到目标值
      Object.keys(mockLogStats).forEach(key => {
        displayLogStats.value[key] = 0
      })
      // 延迟一帧，确保UI更新后再开始动画
      nextTick(() => {
        animateLogStats(mockLogStats)
      })
    } else {
      // 检查哪些数据发生了变化
      const changedStats = {}
      Object.keys(mockLogStats).forEach(key => {
        if (prevLogStats[key] !== mockLogStats[key]) {
          changedStats[key] = mockLogStats[key]
        }
      })

      // 只对变化的数据进行动画
      if (Object.keys(changedStats).length > 0) {
        Object.keys(changedStats).forEach(key => {
          animateLogStat(displayLogStats.value[key], changedStats[key], key)
        })
      }
    }

    console.log('日志统计数据加载成功:', mockLogStats)
  } catch (error) {
    console.error('加载日志统计失败:', error)
  }
}

const currentDate = computed(() => {
  const now = new Date()
  const year = now.getFullYear()
  const month = now.getMonth() + 1
  const day = now.getDate()
  const weekdays = ['日', '一', '二', '三', '四', '五', '六']
  const weekday = weekdays[now.getDay()]

  return `${year}年${month}月${day}日星期${weekday}`
})

const formatNumber = (num) => {
  return num.toLocaleString()
}

const formatCurrency = (amount) => {
  return (amount / 1000).toFixed(1) + 'k'
}

// 按钮跳转处理函数
const handleAddUser = () => {
  router.push('/home/users')
}

const handlePermissionManagement = () => {
  router.push('/home/permissions')
}

const handleSystemSettings = () => {
  router.push('/home/settings')
}

const handleQuickAction = (action) => {
  if (action.route) {
    router.push(action.route)
  }
}

onMounted(async () => {
  // 加载天气数据
  await loadWeatherData()

  // 加载真实数据
  await loadDashboardData()

  // 只有已登录才加载系统状态
  if (userStore.token) {
    await loadSystemStats()
    // 定期刷新数据
    // 系统状态每30秒刷新一次（降低频率）
    setInterval(async () => {
      if (userStore.token) {
        await loadSystemStats()
      }
    }, 30000)
  }

  // 仪表盘数据每2分钟刷新一次（降低频率）
  setInterval(async () => {
    await loadDashboardData()
  }, 120000)

  // 天气数据更新频率更低（每30分钟）
  setInterval(async () => {
    await loadWeatherData()
  }, 1800000)
})
</script>

<style scoped>
.dashboard {
  padding: 24px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
  overflow-x: hidden;
}

/* 欢迎横幅样式 */
.welcome-banner {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 20px;
  padding: 40px;
  margin-bottom: 32px;
  position: relative;
  overflow: hidden;
  box-shadow: 0 10px 40px rgba(102, 126, 234, 0.3);
}

.banner-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  position: relative;
  z-index: 2;
}

.banner-right {
  position: relative;
  z-index: 10;
}

.banner-bg-elements {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1;
}

.bg-circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 6s ease-in-out infinite;
}

.circle-1 {
  width: 200px;
  height: 200px;
  top: -50px;
  right: -50px;
}

.circle-2 {
  width: 120px;
  height: 120px;
  bottom: -30px;
  left: 10%;
  animation-delay: 2s;
}

.circle-3 {
  width: 80px;
  height: 80px;
  top: 50%;
  right: 20%;
  animation-delay: 4s;
}

@keyframes float {

  0%,
  100% {
    transform: translateY(0px) rotate(0deg);
  }

  50% {
    transform: translateY(-20px) rotate(180deg);
  }
}

.main-title {
  font-size: 32px;
  font-weight: 700;
  margin: 0;
  color: white;
  animation: slideInLeft 1s ease-out;
}

.title-underline {
  height: 4px;
  width: 100px;
  background: linear-gradient(90deg, #fbbf24 0%, #f59e0b 100%);
  border-radius: 2px;
  margin-top: 8px;
  animation: expandWidth 1.5s ease-out;
}

@keyframes slideInLeft {
  from {
    transform: translateX(-50px);
    opacity: 0;
  }

  to {
    transform: translateX(0);
    opacity: 1;
  }
}

@keyframes expandWidth {
  from {
    width: 0;
  }

  to {
    width: 100px;
  }
}

.date-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  margin: 16px 0 12px 0;
  color: white;
}

.weather-icon {
  color: #fbbf24;
  animation: pulse 2s infinite;
}

@keyframes pulse {

  0%,
  100% {
    transform: scale(1);
  }

  50% {
    transform: scale(1.1);
  }
}

.subtitle {
  font-size: 14px;
  opacity: 0.9;
  margin: 0 0 24px 0;
  color: white;
}

.quick-stats {
  display: flex;
  gap: 24px;
}

.quick-stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px 16px;
  background: rgba(255, 255, 255, 0.15);
  border-radius: 12px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.quick-stat-number {
  font-size: 20px;
  font-weight: 700;
  color: white;
  margin-bottom: 4px;
  transition: all 0.3s ease;
  transform-origin: center;
}

.quick-stat-number:hover {
  transform: scale(1.05);
}

.quick-stat-label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
}

.action-buttons {
  display: flex;
  gap: 12px;
  margin-bottom: 24px;
  position: relative;
  z-index: 10;
  align-items: flex-start;
  flex-wrap: wrap;
}

.action-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 12px 20px;
  font-weight: 500;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.action-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateY(-2px);
}

.floating-card {
  position: absolute;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(15px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  padding: 12px 16px;
  display: flex;
  align-items: center;
  gap: 8px;
  color: white;
  font-size: 14px;
  animation: floatCards 4s ease-in-out infinite;
  z-index: 1;
}

.card-1 {
  top: 50px;
  right: 0px;
}

.card-2 {
  top: 110px;
  right: -20px;
  animation-delay: 1.5s;
}

.card-3 {
  top: 170px;
  right: 10px;
  animation-delay: 3s;
}

.banner-decoration {
  position: absolute;
  top: 0;
  right: 0;
  width: 300px;
  height: 240px;
  pointer-events: none;
}

@keyframes floatCards {

  0%,
  100% {
    transform: translateY(0px);
  }

  50% {
    transform: translateY(-10px);
  }
}

/* 统计卡片样式 */
.stats-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
  width: 100%;
}

.stat-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 16px;
  transition: all 0.3s ease;
  min-width: 0;
  width: 100%;
}

.stat-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.users-card .stat-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.visits-card .stat-icon {
  background: linear-gradient(135deg, #10b981 0%, #34d399 100%);
}

.pageviews-card .stat-icon {
  background: linear-gradient(135deg, #f59e0b 0%, #fbbf24 100%);
}

.time-card .stat-icon {
  background: linear-gradient(135deg, #ef4444 0%, #f87171 100%);
}

.stat-icon-svg {
  font-size: 24px;
  color: white;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 36px;
  font-weight: 800;
  color: #1a1a1a;
  margin-bottom: 6px;
  transition: all 0.3s ease;
  transform-origin: center;
  letter-spacing: -1px;
  position: relative;
}

.stat-number:hover {
  transform: scale(1.02);
  color: #409eff;
}

.stat-number::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 0;
  height: 2px;
  background: linear-gradient(90deg, #409eff, #67c23a);
  transition: width 0.3s ease;
}

.stat-number:hover::after {
  width: 100%;
}

.stat-number.updating,
.quick-stat-number.updating {
  animation: numberUpdate 2s ease-out;
}

@keyframes numberUpdate {
  0% {
    transform: scale(1);
    color: inherit;
  }

  10% {
    transform: scale(1.05);
    color: #409eff;
    text-shadow: 0 0 10px rgba(64, 158, 255, 0.3);
  }

  100% {
    transform: scale(1);
    color: inherit;
    text-shadow: none;
  }
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
}

.stat-chart {
  width: 80px;
  height: 60px;
}

.mini-chart {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  position: relative;
  overflow: hidden;
}

.mini-chart.blue {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.mini-chart.green {
  background: linear-gradient(135deg, #10b981 0%, #34d399 100%);
}

.mini-chart.orange {
  background: linear-gradient(135deg, #f59e0b 0%, #fbbf24 100%);
}

.mini-chart.red {
  background: linear-gradient(135deg, #ef4444 0%, #f87171 100%);
}

.chart-wave {
  position: absolute;
  width: 100%;
  height: 2px;
  background: rgba(255, 255, 255, 0.6);
  animation: wave 2s infinite;
}

.wave-1 {
  top: 30%;
}

.wave-2 {
  top: 60%;
  animation-delay: 0.5s;
}

@keyframes wave {

  0%,
  100% {
    transform: translateX(-100%);
  }

  50% {
    transform: translateX(100%);
  }
}

/* 新增内容区域 */
.additional-content {
  margin: 32px 0;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
}

.panel-header {
  margin-bottom: 20px;
}

.panel-header h3 {
  font-size: 18px;
  font-weight: 700;
  color: #1a1a1a;
  margin: 0 0 4px 0;
}

.panel-header p {
  font-size: 14px;
  color: #666;
  margin: 0;
}

/* 快捷操作面板 */
.quick-actions-panel {
  background: white;
  border-radius: 16px;
  padding: 28px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.quick-actions-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: #f8fafc;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-item:hover {
  background: #e2e8f0;
  transform: translateY(-2px);
}

.action-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.action-info {
  flex: 1;
}

.action-name {
  font-size: 14px;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 4px;
}

.action-desc {
  font-size: 12px;
  color: #666;
}

.action-arrow {
  color: #cbd5e1;
  transition: all 0.3s ease;
}

.action-item:hover .action-arrow {
  color: #667eea;
  transform: translateX(4px);
}

/* 系统状态监控 */
.system-status-panel {
  background: white;
  border-radius: 16px;
  padding: 28px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.status-grid {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: #f8fafc;
  border-radius: 12px;
}

.status-indicator {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  position: relative;
}

.status-indicator.healthy {
  background: #10b981;
}

.status-indicator.warning {
  background: #f59e0b;
}

.pulse-dot {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: inherit;
  animation: statusPulse 2s infinite;
}

@keyframes statusPulse {
  0% {
    transform: scale(0.8);
    box-shadow: 0 0 0 0 currentColor;
  }

  70% {
    transform: scale(1);
    box-shadow: 0 0 0 10px rgba(255, 255, 255, 0);
  }

  100% {
    transform: scale(0.8);
    box-shadow: 0 0 0 0 rgba(255, 255, 255, 0);
  }
}

.status-info {
  flex: 1;
}

.status-title {
  font-size: 14px;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 4px;
}

.status-value {
  font-size: 12px;
  color: #666;
}

.mini-progress {
  width: 80px;
  height: 6px;
  background: #e5e7eb;
  border-radius: 3px;
  position: relative;
  overflow: hidden;
}

.mini-progress::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: var(--progress);
  background: linear-gradient(90deg, #10b981, #34d399);
  border-radius: 3px;
  transition: width 1s ease-out;
}

.mini-progress.warning::before {
  background: linear-gradient(90deg, #f59e0b, #fbbf24);
}

/* 底部内容 */
.bottom-content {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 24px;
  margin-top: 32px;
}

.recent-activities,
.announcements,
.data-widgets {
  background: white;
  border-radius: 16px;
  padding: 28px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

/* 最近活动 */
.activities-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 20px;
}

.activity-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border-radius: 10px;
  transition: all 0.3s ease;
}

.activity-item:hover {
  background: #f8fafc;
}

.activity-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: 600;
  font-size: 14px;
}

.activity-content {
  flex: 1;
}

.activity-text {
  font-size: 14px;
  margin-bottom: 4px;
}

.user-name {
  font-weight: 600;
  color: #1a1a1a;
}

.activity-action {
  color: #666;
  margin: 0 4px;
}

.activity-target {
  color: #667eea;
  font-weight: 500;
}

.activity-time {
  font-size: 12px;
  color: #9ca3af;
}

.activity-type {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

.activity-type.create {
  background: rgba(16, 185, 129, 0.1);
  color: #10b981;
}

.activity-type.edit {
  background: rgba(245, 158, 11, 0.1);
  color: #f59e0b;
}

.activity-type.delete {
  background: rgba(239, 68, 68, 0.1);
  color: #ef4444;
}

.activities-footer {
  text-align: center;
  border-top: 1px solid #f0f2f5;
  padding-top: 16px;
}

/* 通知公告 */
.announcement-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.announcement-item {
  display: flex;
  gap: 12px;
  padding: 16px;
  border: 1px solid #f0f2f5;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.announcement-item:hover {
  border-color: #667eea;
  background: #f8fafc;
}

.announcement-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-top: 6px;
}

.announcement-indicator.high {
  background: #ef4444;
  box-shadow: 0 0 0 4px rgba(239, 68, 68, 0.2);
}

.announcement-indicator.medium {
  background: #f59e0b;
  box-shadow: 0 0 0 4px rgba(245, 158, 11, 0.2);
}

.announcement-content {
  flex: 1;
}

.announcement-title {
  font-size: 14px;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 6px;
}

.announcement-preview {
  font-size: 12px;
  color: #666;
  line-height: 1.5;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.announcement-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 11px;
  color: #9ca3af;
}

.announcement-category {
  background: #e5e7eb;
  padding: 2px 6px;
  border-radius: 4px;
}

/* 数据概览小组件 */
.widgets-grid {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.widget-item {
  padding: 20px;
  border-radius: 12px;
  color: white;
  transition: all 0.3s ease;
}

.sales-widget {
  background: linear-gradient(135deg, #10b981 0%, #34d399 100%);
}

.orders-widget {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.conversion-widget {
  background: linear-gradient(135deg, #f59e0b 0%, #fbbf24 100%);
}

.widget-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.widget-icon {
  font-size: 20px;
}

.widget-title {
  font-size: 14px;
  font-weight: 500;
  opacity: 0.9;
}

.widget-value {
  font-size: 24px;
  font-weight: 700;
  margin-bottom: 8px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stats-container {
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  }

  .additional-content {
    grid-template-columns: 1fr;
  }

  .bottom-content {
    grid-template-columns: 1fr 1fr;
  }
}

@media (max-width: 768px) {
  .dashboard {
    padding: 16px;
  }

  .welcome-banner {
    padding: 24px;
  }

  .banner-content {
    flex-direction: column;
    gap: 20px;
  }

  .banner-right {
    width: 100%;
  }

  .action-buttons {
    flex-direction: column;
    gap: 12px;
  }

  .action-btn {
    width: 100%;
    justify-content: center;
  }

  .banner-decoration {
    display: none;
  }

  .stats-container {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .bottom-content {
    grid-template-columns: 1fr;
  }

  .quick-actions-grid {
    grid-template-columns: 1fr;
  }
}

/* 角色统计样式 */
.role-stats-section {
  margin: 32px 0;
}

.stats-row {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 24px;
}

.stat-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #667eea, #764ba2);
}

.role-total-card::before {
  background: linear-gradient(90deg, #667eea, #764ba2);
}

.role-active-card::before {
  background: linear-gradient(90deg, #10b981, #34d399);
}

.role-inactive-card::before {
  background: linear-gradient(90deg, #f59e0b, #fbbf24);
}

.stat-icon-wrapper {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.role-active-card .stat-icon-wrapper {
  background: linear-gradient(135deg, #10b981 0%, #34d399 100%);
}

.role-inactive-card .stat-icon-wrapper {
  background: linear-gradient(135deg, #f59e0b 0%, #fbbf24 100%);
}

.stat-icon {
  font-size: 24px;
  color: white;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 36px;
  font-weight: 700;
  line-height: 1;
  margin-bottom: 8px;
  color: #1f2937;
  transition: all 0.3s ease;
}

.stat-number.updating {
  color: #667eea;
  transform: scale(1.05);
}

.stat-label {
  font-size: 16px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 4px;
}

.stat-desc {
  font-size: 14px;
  color: #6b7280;
}

.stat-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  font-weight: 600;
}

.trend-icon {
  font-size: 16px;
}

.trend-icon.up {
  color: #10b981;
}

.trend-icon.down {
  color: #ef4444;
}

.trend-text {
  color: #10b981;
}

.role-inactive-card .trend-text {
  color: #ef4444;
}

/* 日志统计样式 */
.log-stats-section {
  margin: 32px 0;
}

.log-stats-row {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
}

.log-stat-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  border-left: 4px solid transparent;
}

.log-stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
}

.error-card {
  border-left-color: #ef4444;
}

.warning-card {
  border-left-color: #f59e0b;
}

.info-card {
  border-left-color: #3b82f6;
}

.debug-card {
  border-left-color: #10b981;
}

.log-icon-wrapper {
  width: 48px;
  height: 48px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.log-icon-wrapper.error {
  background: rgba(239, 68, 68, 0.1);
  color: #ef4444;
}

.log-icon-wrapper.warning {
  background: rgba(245, 158, 11, 0.1);
  color: #f59e0b;
}

.log-icon-wrapper.info {
  background: rgba(59, 130, 246, 0.1);
  color: #3b82f6;
}

.log-icon-wrapper.debug {
  background: rgba(16, 185, 129, 0.1);
  color: #10b981;
}

.log-icon {
  font-size: 20px;
}

.log-content {
  flex: 1;
}

.log-number {
  font-size: 28px;
  font-weight: 700;
  line-height: 1;
  margin-bottom: 4px;
  color: #1f2937;
  transition: all 0.3s ease;
}

.log-number.updating {
  color: #3b82f6;
  transform: scale(1.05);
}

.log-label {
  font-size: 14px;
  font-weight: 600;
  color: #6b7280;
}

/* 响应式适配 */
@media (max-width: 1200px) {
  .stats-row {
    grid-template-columns: 1fr 1fr;
    gap: 16px;
  }

  .log-stats-row {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
}

@media (max-width: 768px) {
  .stats-row {
    grid-template-columns: 1fr;
  }

  .log-stats-row {
    grid-template-columns: repeat(2, 1fr);
  }

  .stat-card {
    padding: 20px;
    gap: 16px;
  }

  .stat-number {
    font-size: 32px;
  }

  .log-stat-card {
    padding: 16px;
    gap: 12px;
  }

  .log-number {
    font-size: 24px;
  }
}

/* 列表项渐入动画 */
.fade-in-up {
  opacity: 0;
  transform: translateY(20px);
  animation: fadeInUp 0.6s ease-out forwards;
}

@keyframes fadeInUp {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 活动项和公告项的悬停效果增强 */
.activity-item {
  transition: all 0.3s ease;
}

.activity-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.announcement-item {
  transition: all 0.3s ease;
}

.announcement-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}
</style>
